/**
 * Ant Design Pro v4 use `@ant-design/pro-layout` to handle Layout.
 * You can view component api by:
 * https://github.com/ant-design/ant-design-pro-layout
 */
import RightContent from '@/components/GlobalHeader/RightContent';
import Watermark from '@/components/Watermark';
import { ConnectState } from '@/models/connect';
import Authorized from '@/utils/Authorized';
import { getAuthorityFromRouter, isAntDesignPro } from '@/utils/utils';
import ProLayout, {
  BasicLayoutProps as ProLayoutProps,
  DefaultFooter,
  MenuDataItem,
  SettingDrawer,
  Settings,
} from '@ant-design/pro-layout';
import { Button, Result, Tabs } from 'antd';
import { connect } from 'dva';
import React, { useEffect, useState } from 'react';
import { Dispatch } from 'redux';
import { Link, router } from 'umi';
import { formatMessage } from 'umi-plugin-react/locale';
import customSettings from '../../config/customSettings';
import logo from '../assets/logo.svg';
import CustomGlobalTabLayout from '@/components/CustomGlobalTabLayout';
import MenuCN1 from '../locales/zh-CN/menu';
import MenuCN2 from '../locales/zh-CN/menu2';
import route from 'mock/route';
import styles from './Basic.less';


const noMatch = (
  <Result
    status="403"
    title="403"
    subTitle="Sorry, you are not authorized to access this page."
    extra={
      <Button type="primary">
        <Link to="/admin/login">Go Login</Link>
      </Button>
    }
  />
);
export interface BasicLayoutProps extends ProLayoutProps {
  breadcrumbNameMap: {
    [path: string]: MenuDataItem;
  };
  route: ProLayoutProps['route'] & {
    authority: string[];
  };
  settings: Settings;
  user: any;
  dispatch: Dispatch;
}
export type BasicLayoutContext = { [K in 'location']: BasicLayoutProps[K] } & {
  breadcrumbNameMap: {
    [path: string]: MenuDataItem;
  };
};
/**
 * use Authorized check all menu item
 */

const menuDataRender = (menuList: MenuDataItem[]): MenuDataItem[] =>
  menuList.map(item => {
    const localItem = { ...item, children: item.children ? menuDataRender(item.children) : [] };
    return Authorized.check(item.authority, localItem, null) as MenuDataItem;
  });

const defaultFooterDom = (
  <DefaultFooter
    copyright={
      customSettings.footer.copyright != ''
        ? customSettings.footer.copyright
        : '2019 蚂蚁金服体验技术部出品'
    }
    links={
      customSettings.footer.links.length > 0
        ? customSettings.footer.links
        : [
            // {
            //   key: 'Ant Design Pro',
            //   title: 'Ant Design Pro',
            //   href: 'https://pro.ant.design',
            //   blankTarget: true,
            // },
            // {
            //   key: 'github',
            //   title: <Icon type="github" />,
            //   href: 'https://github.com/ant-design/ant-design-pro',
            //   blankTarget: true,
            // },
            // {
            //   key: 'Ant Design',
            //   title: 'Ant Design',
            //   href: 'https://ant.design',
            //   blankTarget: true,
            // },
          ]
    }
  />
);

const footerRender: BasicLayoutProps['footerRender'] = () => {
  if (!isAntDesignPro()) {
    return defaultFooterDom;
  }

  return (
    <>
      {defaultFooterDom}
      <div
        style={{
          padding: '0px 24px 24px',
          textAlign: 'center',
        }}
      >
        <a href="https://www.netlify.com" target="_blank" rel="noopener noreferrer">
          <img
            src="https://www.netlify.com/img/global/badges/netlify-color-bg.svg"
            width="82px"
            alt="netlify logo"
          />
        </a>
      </div>
    </>
  );
};

const BasicLayout: React.FC<BasicLayoutProps> = props => {
  const [isOnline, setIsOnline] = useState<boolean>(true);
  const [pageList, setPageList] = useState<any>([
    {exact: true, label: "首页", name: '', closable: false, path: '/dashboard/crm/report/dashboard/index'},
    {exact: true, label: "客户管理列表", name: '', closable: false, path: '/crm/customer/index'},
  ]);
  const [activeKey, setActiveKey] = useState<any>('');
  const [tabChildrens, setTabChildrens] = useState<any>([]);
  const {
    dispatch,
    children,
    settings,
    location = {
      pathname: '/',
    },
  } = props;
  /**
   * constructor
   */
  const getKeys = (options:any) => {
    var arr:any = [];
    options.map((item:any) =>{
      arr.push(item.key)
    })
    return arr;
  };
  const [openkey, setopenkey] = useState<any>(getKeys(props.route.children));
  useEffect(() => {
    const href = window.location.href;
    const loginInfoStr = localStorage.getItem('user-login-info');
    const loginInfo = JSON.parse(loginInfoStr || '{}');
    const login_name = loginInfo.login_name || '';
    if (dispatch) {
      dispatch({
        type: 'user/fetchCurrent',
      });
      if (
        //用来判断是展示全部菜单还是展示权限菜单
        login_name == 'admin' || customSettings.appName == 'teacher' ||
        href.indexOf('http://localhost:') > -1
       // || customSettings.appName == 'mazex'
      ) {
        setIsOnline(false);
      } else {
        setIsOnline(true);
        dispatch({
          type: 'user/fetchMenuData',
        });
      }
    }
  }, []);

  console.log('props--->', props);
  
  /**
   * init variables
   */

  const handleMenuCollapse = (payload: boolean): void => {
    if (dispatch) {
      dispatch({
        type: 'global/changeLayoutCollapsed',
        payload,
      });
    }
  }; // get children authority

  const authorized = getAuthorityFromRouter(props.route.routes, location.pathname || '/') || {
    authority: undefined,
  };

  const currentUser = props.user.currentUser;

  // 
  const handleClickMenuItem = (e:any) => {
    console.log('menu1111 click->',e)
    
    
  }
  const handleSelectMenuItem = (e:any) => {
    console.log('menu1111 v->',e)

    /**
     * 为什么要用这种方法获取label ？
     *  可以通过合并menu.ts中的数据，但是由于有些菜单是写在组件内部的locales文件中，没有统一在一个文件中，无法进行合并；
     */
    if(customSettings.appName === 'crm'){
      setTimeout(() => {
        let selItem = document.getElementsByClassName('ant-menu-item-selected')[0]?.firstChild?.lastChild.innerText;

        const copyRoute = props.route?.routes || [];
        const key = e.key;
        const selectedKeys = e.selectedKeys;

        let isHas = pageList.filter((v:any) => v.path == key);
        if(isHas && isHas.length == 0){
          const selectMenuItem = findSelectMenuItem(copyRoute, key);
          // selectMenuItem.label = getMenuItemLabel(selectMenuItem.name);
          selectMenuItem.label = selItem;
          setActiveKey(selectMenuItem.path);
          let copyPageList = JSON.parse(JSON.stringify(pageList));
          copyPageList.push(selectMenuItem);
          
          console.log(copyPageList)
          setPageList(copyPageList);
          setTabChildrens((o:any) => {
            return [
              ...o, 
              {
                [selectMenuItem.path] : props.children
              }
            ]
          });
        }else{
          setActiveKey(key);
        }
      }, 10);
    }
    
  }

  const findSelectMenuItem = (r:any, key:any) => {
    // debugger
    for(let i = 0; i < r.length; i++) {
      // console.log('c->', i, r.length,r[i])
      if(r[i].path && r[i].path == key){
        return r[i];
      }else{
        if(r[i].routes){
          let v:any = findSelectMenuItem(r[i].routes, key);
          if(v){
            console.log('v......',v)
            return v;
          } 
        } 
      }
    }
  }
  const getMenuItemLabel = (v:any) => {
    const menuLocales = Object.assign(MenuCN1, MenuCN1);
    console.log('menuLocales->',menuLocales)
    for(let k in menuLocales){
      if(k.indexOf(`.${v}`) > -1){
        return menuLocales[k];
      }
    }
  }

  const handleSetActiveKey = (v:any) => {
    setActiveKey(v);
    router.push(v);
  }

  const handleEditTabs = (v:any) => {
    
    let copyPageList = JSON.parse(JSON.stringify(pageList));
    let delIndex = 0;
    copyPageList.forEach((val:any, index:any) => {
      if(val.path == v){
        delIndex = index;
      }
    });
    // console.log('vv',delIndex, copyPageList);
    activeKey == v && handleSetActiveKey(copyPageList[delIndex - 1].path);
    copyPageList.splice(delIndex, 1);
    setPageList(copyPageList);
  }

  return (
    <div className={customSettings.isRow == true ? styles.menu :styles.fix}>
      <ProLayout
        logo={customSettings.logo !== '' ? customSettings.logo : logo}
        menuProps={{
          onClick: handleClickMenuItem,
          onSelect: handleSelectMenuItem,
        }}
        // menuRender={menuRender}
        menuHeaderRender={(logoDom, titleDom) => (
          <Link to="/">
            {logoDom}
            {titleDom}
          </Link>
        )}
        onCollapse={handleMenuCollapse}
        menuItemRender={(menuItemProps, defaultDom) => {
          if (menuItemProps.isUrl || menuItemProps.children || !menuItemProps.path) {
            return defaultDom;
          }

          return <Link to={menuItemProps.path}>{defaultDom}</Link>;
        }}
        //面包屑
        breadcrumbRender={(routers = []) => [
          {
            path: '/',
            breadcrumbName: formatMessage({
              id: 'menu.home',
              defaultMessage: 'Home',
            }),
          },
          ...routers,
        ]}
        openKeys={customSettings.isRow == true ? openkey:undefined}
        itemRender={(route, params, routes, paths) => {
          const first = routes.indexOf(route) === 0;
          return first ? (
            <Link to={paths.join('/')}>{route.breadcrumbName}</Link>
          ) : (
            <span>{route.breadcrumbName}</span>
          );
        }}
        siderWidth={customSettings.isWidth == true ? 208:256}
        footerRender={footerRender}
        // 修改此处从接口获取路由
        // menuDataRender={menuDataRender}
        menuDataRender={isOnline ? () => props.user.menuData || [] : menuDataRender}
        formatMessage={formatMessage}
        rightContentRender={() => <RightContent location={location} />}
        {...props}
        {...settings}
      >
        <Authorized authority={authorized!.authority} noMatch={noMatch}>
        {customSettings.appName === 'crm' && (
        <CustomGlobalTabLayout 
          children={children} 
          pageList={pageList} 
          activeKey={activeKey} 
          setActiveKey={(v:string)=>handleSetActiveKey(v)} 
          tabChildrens={tabChildrens}
          editTabs={(v:any) => handleEditTabs(v)}
        ></CustomGlobalTabLayout>
        )}
        {children}
        </Authorized>
        {customSettings.appName === 'crm' && (
          <Watermark label={`${currentUser.login_name || ''} ${currentUser.nickname || ''}`} />
        )}
      </ProLayout>
      <SettingDrawer
        settings={settings}
        onSettingChange={config =>
          dispatch({
            type: 'settings/changeSetting',
            payload: config,
          })
        }
      />
    </div>
  );
};

export default connect(({ global, settings, user }: ConnectState) => ({
  collapsed: global.collapsed,
  settings,
  user,
}))(BasicLayout);
